let http = require("http");
let url = require("url");
let fs = require("fs");
let path = require("path");
let querystring = require("querystring");

let server = http.createServer();

server.on("request", function (req, resp) {
    let reqUrl = url.parse(req.url);
    resp.setHeader("Content-Type", "text/html; charset=utf-8");
    if (!reqUrl.pathname.endsWith("favicon.ico")) {
        console.log(reqUrl);
        // console.log(req.method);
        // console.log(req.method.toLowerCase() == "get");
        if (req.method.toLowerCase() == "get") {
            //处理get请求
            if (reqUrl.pathname.endsWith("/demo.html")) {
                let htmlPath = path.join(__dirname, "demo.html");
                // console.log(htmlPath);
                fs.readFile(htmlPath, "utf-8", function (err, data) {
                    console.log(data);
                    resp.end(data);
                });
            }
            // console.log("1")
        } else if (req.method.toLowerCase() == "post") {
            //处理post请求
            let paramsStr = "";
            if (reqUrl.pathname.endsWith("/loginPost")) {
                req.on("data", arg => {
                    paramsStr += arg;
                });
                req.on("end", () => {
                    let params = querystring.parse(paramsStr);
                    console.log(params);
                    //判断账号和密码
                    if (params.account == "admin" && params.password == "123") {
                        //登录成功
                        let htmlPath = path.join(__dirname, "welcome.html");
                        fs.readFile(htmlPath, "utf-8", function (err, data) {
                            resp.end(data);
                        });
                    } else {
                        //登录失败
                        //重定向到登录页面，并带上错误信息参数
                        let loginHref = new URL("http://localhost:8080/login.html");
                        //创建请求对象
                        let request = http.request(loginHref, (resp) => {
                            console.log("request:::resp");
                            // resp.end();
                        });
                        //结束请求
                        request.end();
                    }
                });
            }
        } else {
            resp.end("非法访问");
        }
    }

});

server.listen(8080, () => console.log("服务器启动成功"));